function fibers = bvqx_dtsf_parsefibers(fid, numfib)
% bvqx_dtsf_parsefibers  - parse fibers from DTSF file
%
% FORMAT:       fibers = bvqx_dtsf_parsefibers(fid, numfib)
%
% Input fields:
%
%       fid         input file fid (fopen)
%       numfib      number of fibers
%
% Output fields
%
%       fibers      Nx1 struct array with fields
%        .NrOfPoints   number of points for that fiber
%        .Selected     uint8, either 0 or 1
%        .RGB          1x3 uint8 array
%        .FromToPoint  1x2 double array, [0, NrOfPoints]
%        .Coord        Px3 coordinates of fiber points
%
% See also BVQXfile, bffio

% Version:  v0.8a
% Build:    9102221
% Date:     Oct-21 2009, 3:50 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
   ~isa(fid, 'double') || ...
    isempty(fid) || ...
   ~isreal(fid) || ...
   ~any(fopen('all') == fid(1)) || ...
   ~isa(numfib, 'double') || ...
    numel(numfib) ~= 1 || ...
   ~isreal(numfib) || ...
    isnan(numfib) || ...
    isinf(numfib) || ...
    numfib < 0
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad or missing argument.' ...
    );
end

% build structure first, so we don't need growing it later!
fibers = struct;
fibers.NrOfPoints  = 1;
fibers.Selected    = 0;
fibers.RGB         = [0, 0, 0];
fibers.FromToPoint = [0, 1];
fibers.Coord       = [0, 0, 0];
if numfib < 1
    fibers(:) = [];
    return;
end
fibers(2:numfib) = fibers;

% try reading
try

    % loop over fibers
    for fc = 1:numfib

        % get number of points
        numpts = fread(fid, [1, 1], 'uint32=>double');
        fibers(fc).NrOfPoints  = numpts;
        fibers(fc).Selected    = fread(fid, [1, 1], '*uint8');
        fibers(fc).RGB         = fread(fid, [1, 3], '*uint8');
        fibers(fc).FromToPoint = fread(fid, [1, 2], 'uint32=>double');
        fibers(fc).Coord       = fread(fid, [3, numpts], 'single=>double')';
    end

catch
    rethrow(lasterror);
end
